package com.treeroot.treenet.protocol.abs.tcp.route;

import com.treeroot.treenet.protocol.abs.tcp.decode.DecodedMessage;
import com.treeroot.treenet.protocol.abs.tcp.session.TcpSession;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description: 默认消息路由器
 * Create By TreeRoot
 * Create Time: 2025/06/02 10:19
 * Class Name: DefaultMessageRouter
 *
 * @author TreeRoot
 */
@Slf4j
public class DefaultMessageRouter implements MessageRouter {

    // 线程安全 map 存储 handler
    private final Map<String, RouteHandler> handlerMap = new ConcurrentHashMap<>();

    @Override
    public void registerHandler(String messageType, RouteHandler handler) {
        handlerMap.put(messageType, handler);
        log.info("[Router] 注册消息类型处理器: {}", messageType);
    }

    @Override
    public void route(DecodedMessage message, TcpSession session) throws IOException {
        String messageType = message.getType();
        RouteHandler handler = handlerMap.get(messageType);
        if (handler != null) {
            handler.handle(message, session);
        } else {
            log.warn("[Router] 未找到对应的处理器: {}", messageType);
        }
    }
}